<template>
  <div class="column-management">
    <div class="page-header">
      <h2>专栏管理</h2>
    </div>

    <!-- 搜索区域 -->
    <div class="search-area">
      <el-form :model="searchForm" inline>
        <el-form-item label="专栏信息">
          <el-input v-model="searchForm.columnInfo" placeholder="请输入专栏信息" clearable />
        </el-form-item>
        <el-form-item label="专栏状态">
          <el-select v-model="searchForm.columnState" placeholder="请选择状态" clearable>
            <el-option label="上架" :value="1" />
            <el-option label="下架" :value="0" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="searchColumns">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="resetSearch">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
          <el-button type="primary" @click="showAddDialog = true">
            <el-icon><Plus /></el-icon>
            新增专栏
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <div class="table-area">
      <el-table :data="columnList" v-loading="loading" stripe>
        <el-table-column prop="columnId" label="专栏ID" width="80" />
        <el-table-column prop="columnInfo" label="专栏信息" width="200" />
        <el-table-column prop="columnPrice" label="专栏价格" width="120">
          <template #default="{ row }">
            ¥{{ row.columnPrice?.toFixed(2) || '0.00' }}
          </template>
        </el-table-column>
        <el-table-column prop="subscribeNum" label="订单量" width="100" />
        <el-table-column prop="columnCourseNum" label="专栏数量" width="120">
          <template #default="{ row }">
            <el-tag type="info">{{ row.columnCourseNum || 0 }} 个课程</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="columnState" label="专栏状态" width="120">
          <template #default="{ row }">
            <el-tag :type="row.columnState === 1 ? 'success' : 'danger'">
              {{ getColumnStateText(row.columnState) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="180" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button size="small" @click="editColumn(row)">
              <el-icon><Edit /></el-icon>
              编辑
            </el-button>
            <el-button size="small" type="danger" @click="deleteColumn(row.columnId)">
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      :title="isEdit ? '编辑专栏' : '新增专栏'"
      v-model="showAddDialog"
      width="600px"
      @close="resetForm"
    >
      <el-form :model="columnForm" :rules="columnRules" ref="columnFormRef" label-width="100px">
        <el-form-item label="专栏信息" prop="columnInfo">
          <el-input v-model="columnForm.columnInfo" placeholder="请输入专栏信息" />
        </el-form-item>
        <el-form-item label="专栏价格" prop="columnPrice">
          <el-input-number v-model="columnForm.columnPrice" :min="0" :precision="2" placeholder="请输入专栏价格" />
        </el-form-item>
        <el-form-item label="订单量" prop="subscribeNum">
          <el-input-number v-model="columnForm.subscribeNum" :min="0" placeholder="请输入订单量" />
        </el-form-item>
        <el-form-item label="专栏数量" prop="columnCourseNum">
          <el-input-number v-model="columnForm.columnCourseNum" :min="0" placeholder="请输入专栏数量" />
        </el-form-item>
        <el-form-item label="专栏状态" prop="columnState">
          <el-select v-model="columnForm.columnState" placeholder="请选择状态">
            <el-option label="上架" :value="1" />
            <el-option label="下架" :value="0" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAddDialog = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Search, Refresh, Edit, Delete } from '@element-plus/icons-vue'
import { columnApi } from '@/api/column'

// 响应式数据
const loading = ref(false)
const columnList = ref([])
const showAddDialog = ref(false)
const isEdit = ref(false)
const columnFormRef = ref()

// 搜索表单
const searchForm = reactive({
  columnInfo: '',
  columnState: null
})

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 10,
  total: 0
})

// 专栏表单
const columnForm = reactive({
  columnId: null,
  columnInfo: '',
  columnPrice: 0,
  subscribeNum: 0,
  columnCourseNum: 0,
  columnState: 1
})

// 表单验证规则
const columnRules = {
  columnInfo: [
    { required: true, message: '请输入专栏信息', trigger: 'blur' }
  ],
  columnPrice: [
    { required: true, message: '请输入专栏价格', trigger: 'blur' }
  ],
  columnState: [
    { required: true, message: '请选择专栏状态', trigger: 'change' }
  ]
}

// 获取专栏状态文本
const getColumnStateText = (state) => {
  const stateMap = {
    1: '上架',
    0: '下架'
  }
  return stateMap[state] || '未知'
}

// 搜索专栏
const searchColumns = async () => {
  loading.value = true
  try {
    const response = await columnApi.getColumnList(searchForm)
    if (response.code === 200) {
      columnList.value = response.data || []
      pagination.total = columnList.value.length
    }
  } catch (error) {
    console.error('搜索专栏失败:', error)
  } finally {
    loading.value = false
  }
}

// 重置搜索
const resetSearch = () => {
  Object.assign(searchForm, {
    columnInfo: '',
    columnState: null
  })
  searchColumns()
}

// 编辑专栏
const editColumn = (row) => {
  isEdit.value = true
  Object.assign(columnForm, row)
  showAddDialog.value = true
}

// 删除专栏
const deleteColumn = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这个专栏吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const response = await columnApi.deleteColumn(id)
    if (response.code === 200) {
      ElMessage.success('删除成功')
      searchColumns()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除专栏失败:', error)
    }
  }
}

// 提交表单
const submitForm = async () => {
  try {
    await columnFormRef.value.validate()

    const response = isEdit.value
      ? await columnApi.updateColumn(columnForm)
      : await columnApi.addColumn(columnForm)

    if (response.code === 200) {
      ElMessage.success(isEdit.value ? '修改成功' : '新增成功')
      showAddDialog.value = false
      searchColumns()
    }
  } catch (error) {
    console.error('提交失败:', error)
  }
}

// 重置表单
const resetForm = () => {
  Object.assign(columnForm, {
    columnId: null,
    columnInfo: '',
    columnPrice: 0,
    subscribeNum: 0,
    columnCourseNum: 0,
    columnState: 1
  })
  isEdit.value = false
  columnFormRef.value?.resetFields()
}

// 分页处理
const handleSizeChange = (val) => {
  pagination.pageSize = val
  searchColumns()
}

const handleCurrentChange = (val) => {
  pagination.currentPage = val
  searchColumns()
}

// 初始化
onMounted(() => {
  searchColumns()
})
</script>

<style scoped>
.column-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-area {
  background: white;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.table-area {
  background: white;
  padding: 20px;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.pagination {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}
</style>